package com.itheima.service.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @PackageName: com.itheima.service.impl
 * @ClassName: RoleServiceImpl
 * @Author: zhouyangyang
 * @Date: 2020/2/17 10:04
 * @Description:
 */
@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    /**
     *分页查询
     *@returns
     */
    public PageResult findByCondition(QueryPageBean queryPageBean) {
        //使用pagehelper查询
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        String queryString = queryPageBean.getQueryString();
        if (StringUtils.isNotEmpty(queryString)){
            queryString = "%"+queryString+"%";
        }
        Page<Role> page = roleDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     *新增角色
     *@returns
     */
    public void add(Role role, Integer[] permissionIds) {
        roleDao.add(role);
        //调用方法,添加关系
        setRoleAndPermission(role.getId(),permissionIds);
    }

    /**
     *根据id查找角色信息
     *@returns
     */
    public Role findById(Integer id) {
        return roleDao.findById(id);
    }

    /**
     *根据角色id查询对应的权限id
     *@returns
     */
    public Integer[] findPermissionIdsByRoleId(Integer id) {
        return roleDao.findpermissionIdsByRoleId(id);
    }

    /**
     *编辑角色
     *@returns
     */
    public void edit(Role role, Integer[] ids) {
        //修改角色基本信息
        roleDao.edit(role);
        //删除原有角色和权限的关系
        roleDao.deleteRoleAndPermissionByRoleId(role.getId());
        //添加角色和权限的关系
        setRoleAndPermission(role.getId(),ids);
    }

    /**
     *删除角色
     *@returns
     */
    public void deleteById(Integer id) {
        //先删除角色和权限的关联关系
        roleDao.deleteRoleAndPermissionByRoleId(id);
        //删除角色
        roleDao.deleteRoleById(id);
    }

    /**
     *添加角色和权限之间的关系
     *@returns
     */
    public void setRoleAndPermission(Integer roleId,Integer[] permissionIds){
        if (permissionIds != null && permissionIds.length >0){
            for (Integer permissionId : permissionIds) {
                Map<String,Object> map = new HashMap<>();
                map.put("role_id",roleId);
                map.put("permission_id",permissionId);
                roleDao.setRoleAndPermission(map);
            }
        }
    }
}
